<template>
  <el-input
    v-bind="$attrs"
    v-on="{
      ...$listeners,
      input: onInput
    }"
    :value="showValue"
  ></el-input>
</template>

<script>
/**
 * el-input 输入框、携带正则表达式验证，通过正则表达式才进行赋值
 * inputLimit
 * 注意：优先顺序，RegExp ==> limitList
 * @author zhoufei
 */
import { isRegExp } from '@/utils'
import { decimalRE, intergerRE } from '@/utils/validate'

const limitList = [
  /* 小数、包含正整数、开头只能为一个零 */
  { name: 'decimal', regexp: decimalRE },
  /* 正整数 */
  { name: 'number', regexp: intergerRE }
]

export default {
  name: 'ElInputLimit',
  props: {
    value: {
      type: [String, Number]
    },
    // 输入限制、 decimal | number
    // 优先顺序，RegExp ==> limitList
    inputLimit: {
      type: [String, RegExp],
      validator: function(val) {
        if (val) {
          if (isRegExp(val)) {
            return true
          }
          return !!limitList.find(item => item.name === val)
        } else {
          return true
        }
      }
    }
  },
  data() {
    return {
      showValue: this.value,
      vRegexp: ''
    }
  },

  created() {
    this.setRegexp()
  },

  watch: {
    value(val) {
      this.showValue = val
    },
    inputLimit: 'setRegexp'
  },

  methods: {
    setRegexp() {
      const { inputLimit } = this
      if (!inputLimit) {
        this.vRegexp = ''
        return
      }
      if (isRegExp(inputLimit)) {
        this.vRegexp = inputLimit
        return
      }
      if (inputLimit) {
        const limit = limitList.find(item => item.name === inputLimit)
        if (limit) {
          this.vRegexp = limit.regexp
        } else {
          this.vRegexp = ''
        }
      }
    },

    onInput(val) {
      if (val !== undefined && val !== '') {
        const re = this.vRegexp
        if (re) {
          if (!re.test(val)) {
            return
          }
        }
      }

      this.$emit('input', val)
    }
  }
}
</script>
